// @Author miaoqing
// @Date 2024/02/27 16:47:00
// @Desc
package logic

import (
	"core/command"
	"core/component/logger"
	"sync"
)

var (
	orrOnce         sync.Once
	onlineServerMgr *OnlineServerMgr
)

type OnlineServerMgr struct {
	endpoints *sync.Map
}

func onlineServerMgrGetMe() *OnlineServerMgr {
	orrOnce.Do(func() {
		onlineServerMgr = &OnlineServerMgr{
			endpoints: &sync.Map{},
		}
	})
	return onlineServerMgr
}

func (mgr *OnlineServerMgr) addOnlineClient(sc *OnlineClient, srvID, srvAddr string, handleMsgs []uint32, proIndx uint32) {
	val, ok := mgr.endpoints.Load(srvID)
	if ok {
		oldClient, _ := val.(*OnlineClient)
		if sc != oldClient {
			oldClient.Close()
		}
	}
	sc.srvID = srvID
	sc.srvAddr = srvAddr
	sc.processIdx = proIndx
	//for _, id := range handleMsgs {
	//	sc.handleMsgs = append(sc.handleMsgs, uint16(id))
	//}
	mgr.endpoints.Store(srvID, sc)
	logger.Infof("Online服务器连接到Pvp服务器 OnlineServer:%v Pvp:%v", srvID, ServerInstance().srvID)
}

func (mgr *OnlineServerMgr) removeServerClient(srvID string) {
	_, ok := mgr.endpoints.Load(srvID)
	if !ok {
		return
	}
	mgr.endpoints.Delete(srvID)
}

func (mgr *OnlineServerMgr) sendMsgToOnlineServer(srvID string, cmd command.Command, msg interface{}) bool {
	client, ok := mgr.endpoints.Load(srvID)
	if !ok {
		logger.Error("client not find,srvId:", srvID)
		return false
	}
	return client.(*OnlineClient).sendMsg(cmd, msg)
}

func (mgr *OnlineServerMgr) sendMsgToOnlinePlayer(srvID string, playerID uint64, cmd command.Command, msg interface{}) bool {
	client, ok := mgr.endpoints.Load(srvID)
	if !ok {
		logger.Error("client not find,srvId:", srvID, ",player ID:", playerID)
		return false
	}
	return client.(*OnlineClient).sendMsgToPlayer(playerID, cmd, msg)
}
